package com.dp.mallchat.common.common.exception;

import com.dp.mallchat.common.common.domain.enums.CommonErrorEnum;
import com.dp.mallchat.common.common.domain.vo.resp.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @Author: dupeng
 * @CreateTime: 2024-06-04  11:25
 * @Description: 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler{

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult<?> methodArgumentNotValidException(MethodArgumentNotValidException e){
        String message = e.getBindingResult().getFieldErrors().stream().map(f -> f.getField() + f.getDefaultMessage() + ",").collect(Collectors.joining());
        return ApiResult.fail(CommonErrorEnum.PARAM_VALID.getErrorCode(),message.substring(0, message.length()-1));
    }

    @ExceptionHandler(BusinessException.class)
    public ApiResult<?> businessException(BusinessException e){
        log.info("business exception！The reason is：{}", e.getMessage(), e);
        return ApiResult.fail(e.errorCode, e.errorMsg);
    }

    @ExceptionHandler(Throwable.class)
    public ApiResult<?> methodArgumentNotValidException(Throwable e){
        log.error("System error, The reason is：{}",e.getMessage(),e);
        return ApiResult.fail(CommonErrorEnum.SYSTEM_ERROR);
    }


}
